package com.zzkrst.modules.generator.controller;

import cn.hutool.core.io.IoUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.common.collect.Maps;
import com.zzkrst.modules.generator.model.GeneratorParam;
import com.zzkrst.modules.generator.service.SysGeneratorService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.*;
import com.zzkrst.common.api.vo.Result;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @Author: zlt
 */
@RestController
@Api(tags = "代码生成器")
@RequestMapping("/code/generator")
public class SysGeneratorController {
    @Autowired
    private SysGeneratorService sysGeneratorService;

    /**
     * 列表
     */
    @ResponseBody
    @GetMapping("/list")
    public Result<?> getTableList(String tableName,@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo, @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        IPage<List<Map<String, Object>>> maps = sysGeneratorService.queryList(tableName,pageNo,pageSize);
        return Result.OK(maps);
    }


    /**
     * 查看
     */
    @ResponseBody
    @GetMapping("/view")
    public Result<?> queryColumns(String tableName) {
        Map<String,Object> result = Maps.newHashMap();
        result.put("columns",sysGeneratorService.queryColumns(tableName));
        result.put("generatorData",sysGeneratorService.queryGeneratorParam(tableName));
        return Result.OK(result);
    }


    /**
     * 生成代码FileUtil
     */
    @PostMapping("/code")
    public void makeCode(@RequestBody GeneratorParam param, HttpServletResponse response) throws IOException {
        byte[] data = sysGeneratorService.generatorCode(param);
        response.reset();
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION,
                String.format("attachment; filename=%s.zip", param.getTableName()));
        response.addHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(data.length));
        response.setContentType("application/octet-stream; charset=UTF-8");

        IoUtil.write(response.getOutputStream(), Boolean.TRUE, data);
    }
}
